const app = getApp()
import {
  validate
} from '../../../common/js/validate'
import {
  decryptData,
  encryptionData
} from '../../../utils/public'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    name: '',
    mobile: '',
    patientId: '',
    payId: '',
    mark: '',
    first: '',
    responsible: '',
    nameErr: false,
    mobileErr: false,
    patientIdErr: false,
    disabled: true,
    firtsOptions: [{
        label: "张医生",
        value: "张医生"
      },
      {
        label: "王医生",
        value: "王医生"
      },
      {
        label: "孙医生",
        value: "孙医生"
      },
      {
        label: "李医生",
        value: "李医生"
      },
      {
        label: "周医生",
        value: "周医生"
      },
      {
        label: "吴医生",
        value: "吴医生"
      },
    ],
    responsibleOptions: [],
    addFrom: {},
    //蓝牙参数
    BTLTEST: '',
    btnFis: false,
    type: 1,
    deviceId: '',
    UUID1: '', //服务
    UUID2: '', //特征
    serviceId: '',
    characteristicId: '',
    commandEnd: '', //最终指令
    commandStart: '', //最初指令
    deviceNo: '', //设备编号
    orderNo: '', //订单编号
    isLock: null,
    modelid: wx.getStorageSync('modelid')
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.removeStorageSync('timeiS')
    let newfrom = JSON.parse(options.ovtData)
    let addFromNew = {}
    addFromNew.treatmentIds = newfrom.selected
    addFromNew.treatmentOfDays = newfrom.hour
    addFromNew.projectOfDays = newfrom.day
    addFromNew.typessd = newfrom.type
    console.log(newfrom);
    this.setData({
      addFrom: addFromNew
    })
    this.getList()
    this.updateDisabled()
  },
  showDialog({
    title,
    tip,
    icon
  } = {}) {
    this.setData({
      title: title,
      tip: tip,
      icon: icon
    })
    this.selectComponent('#dialog').show()
  },
  shouquan() {
    wx.openSetting()
  },
  showDialogsq({
    title,
    tip,
    icon
  } = {}) {
    this.setData({
      title: title,
      tip: tip,
      icon: icon
    })
    this.selectComponent('#dialogsq').show()
  },
  showDialogt({
    title,
    tip,
    icon
  } = {}) {
    this.setData({
      title: title,
      tip: tip,
      icon: icon
    })
    this.selectComponent('#dialogt').show()
  },
  createBLEConnection(deviceId) {
    let that = this
    wx.showLoading({
      title: '设备搜索中',
      mask: true
    })
    let trimA = setTimeout(() => {
      if (wx.getStorageSync('timeiS')) {
        if (wx.getStorageSync('timeiS') >= 2) {
          that.showDialog({
            title: '蓝牙未响应',
            icon: 'fail',
            tip: ['请前往设置-应用内打开手机蓝牙', '请勿下拉打开蓝牙！']
          })
          setTimeout(() => {
            wx.navigateBack({
              delta: 1,
            })
          }, 2000)
        } else {
          wx.setStorageSync('timeiS', Number(wx.getStorageSync('timeiS')) + 1)
          that.showDialogt({
            title: '蓝牙未响应',
            icon: 'fail',
            tip: ['请重新打开设备蓝牙', '并重新扫描二维码。']
          })
        }
      } else {
        wx.setStorageSync('timeiS', 1)
        that.showDialogt({
          title: '蓝牙未响应',
          icon: 'fail',
          tip: ['请重新打开设备蓝牙', '并重新扫描二维码。']
        })
      }
      wx.closeBLEConnection()
      wx.closeBluetoothAdapter()
      clearTimeout(trimA)
      trimA = null
      wx.hideLoading()
    }, 5000)
    wx.createBLEConnection({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId,
      success(rest) {
        wx.hideLoading()
        wx.removeStorageSync('timeiS')
        clearTimeout(trimA)
        trimA = null
        setTimeout(() => {
          that.getBLEDeviceServices(deviceId);
        }, 1000)
        wx.stopBluetoothDevicesDiscovery({
          success(res) {}
        });
      },
      fail(err) {
        wx.closeBLEConnection()
        wx.closeBluetoothAdapter()
        // if(trimA){
        //   that.showDialog({
        //     title: '蓝牙访问失败',
        //     icon: 'fail',
        //     tip: ['请重新扫码']
        //   })
        // }
        // clearTimeout(trimA)
        // trimA = null
        // wx.hideLoading()
        that.setData({
          btnFis: false
        })

      }
    });
  },
  colsFun() {
    wx.navigateBack({
      delta: 2,
    })
  },
  restecode() {
    let that = this
    let resp = that.data.resp
    wx.scanCode({
      onlyFromCamera: true,
      success: (resCode) => {
        console.log(resCode);
        if (resCode.errMsg == "scanCode:ok") {
          console.log(resCode, '扫码内容');
          if (!resCode.result.match(RegExp(/便携式低频脉冲治疗仪/))) {
            that.showDialogt({
              title: '无效二维码',
              icon: 'fail',
              tip: ['请扫描设备背部二维码']
            })
            return
          }
          let A = resCode.result.indexOf(';')
          let B = resCode.result.indexOf(';', A + 1)
          let deviceNo = resCode.result.substring(A + 1, B)
          wx.request({
            url: app.globalData.serverUrl + '/device/check/' + deviceNo,
            method: 'GET',
            header: {
              'token': wx.getStorageSync('token')
            },
            success: (resdeviceNo => {
              if (resdeviceNo.data.code == 200) {
                let newYCL = resCode.result.slice(0, resCode.result.indexOf(';'))
                wx.setStorageSync('chb_key', that.addObjret(newYCL));
                that.setData({
                  btnFis: false,
                  BTLTEST: that.addObjret(newYCL),
                  deviceNo: deviceNo,
                  orderNo: resp.data.orderInfo.orderNo
                })
                if (that.data.modelid == 'iPhone') {
                  that.startBluetoothDeviceDiscovery()
                } else {
                  wx.openBluetoothAdapter({
                    success: (res) => {
                      console.log(res);
                      //已打开
                      wx.getBluetoothAdapterState({
                        //蓝牙的匹配状态
                        success: (res1) => {
                          console.log(res1, "本机设备的蓝牙已打开");
                          //生成密钥存储
                          let keys;
                          keys = wx.getStorageSync('chb_key').split(':')
                          wx.setStorageSync('key_K', that.keysfun(keys))
                          that.setData({
                            deviceId: wx.getStorageSync('chb_key')
                          })
                          wx.setStorageSync('deviceId', wx.getStorageSync('chb_key'))
                          that.createBLEConnection(wx.getStorageSync('chb_key'))
                        },
                        fail(error) {
                          that.showDialog({
                            title: '手机蓝牙未打开',
                            icon: 'fail',
                            tip: ['请前往设置-应用内打开', '手机蓝牙']
                          })
                          that.setData({
                            btnFis: false
                          })
                        },
                      });
                    },
                    fail: (err) => {
                      console.log(err);
                      that.showDialog({
                        title: '手机蓝牙未打开',
                        icon: 'fail',
                        tip: ['请前往设置-应用内打开', '手机蓝牙']
                      })
                      that.setData({
                        btnFis: false
                      })
                    }
                  })

                }
              } else if (resdeviceNo.data.code == 5016) {
                that.showDialogt({
                  title: '该设备已出租',
                  icon: 'fail',
                  tip: ['请将设备归还后在进行配置']
                })
                wx.closeBluetoothAdapter()
              } else if (resdeviceNo.data.code == 5012) {
                that.showDialogt({
                  title: '该设备已损坏',
                  icon: 'fail',
                  tip: ['请联系厂家维修设备']
                })
                wx.closeBluetoothAdapter()
              } else if (resdeviceNo.data.code == 5015) {
                that.showDialogt({
                  title: '非本科室设备',
                  icon: 'fail',
                  tip: ['非本科室设备无法', '进行任何操作']
                })
                wx.closeBluetoothAdapter()
              } else if (resdeviceNo.data.code == 5013) {
                that.showDialogt({
                  title: resdeviceNo.data.message,
                  icon: 'fail',
                  tip: ['']
                })
                wx.closeBluetoothAdapter()
              } else {
                if (resdeviceNo.data.message.indexOf(',')) {
                  let arr = resdeviceNo.data.message.split(',')
                  let arr1 = []
                  arr.map((item, index) => {
                    if (index != 0) {
                      arr1.push(item)
                    }
                  })
                  that.showDialog({
                    title: arr[0],
                    icon: 'fail',
                    tip: [arr1]
                  })
                  wx.closeBluetoothAdapter()
                } else {
                  that.showDialog({
                    title: resdeviceNo.data.message,
                    icon: 'fail',
                    tip: ['']
                  })
                  wx.closeBluetoothAdapter()
                }
              }
            })
          })
        } else {
          that.setData({
            btnFis: false
          })
          app.showMsg('无效二维码!')
        }
      },
      fail() {
        if(resp.data.orderInfo.totalFee == 0 && resp.data.orderInfo.operationType == 1 ){
          wx.request({
            url: app.globalData.serverUrl + '/ddOrder/delete/' + resp.data.orderInfo.orderNo,
            method: 'GET',
            header: {
              'token': wx.getStorageSync('token')
            },
            success:delres=>{
              console.log(delres.data.code);
              if(delres.data.code==200){
                wx.reLaunch({
                  url: '/pages/workbench/workbench',
                })
              }else{
                if (delres.data.message.indexOf(',')) {
                  let arr = delres.data.message.split(',')
                  let arr1 = []
                  arr.map((item, index) => {
                    if (index != 0) {
                      arr1.push(item)
                    }
                  })
                  that.showDialog({
                    title: arr[0],
                    icon: 'fail',
                    tip: [arr1]
                  })
                } else {
                  that.showDialog({
                    title: delres.data.message,
                    icon: 'fail',
                    tip: ['']
                  })
                }
              }
              
            },
            fail(){

            }
          })
          
        }else{
          wx.navigateTo({
            url: '/pagesA/orderswaiters/orderswaiters?id=' + resp.data.orderInfo.orderNo
          })
        }
        
      }
    })
  },
  getList() {
    let that = this
    wx.request({
      url: app.globalData.serverUrl + '/staff/list',
      method: 'GET',
      header: {
        'token': wx.getStorageSync('token')
      },
      success: (res => {
        let resData = res.data
        if (resData.code == 200) {
          resData.data.staffList.map(item => {
            item.label = item.staffName
            item.value = item.staffId
          })
          that.setData({
            responsibleOptions: resData.data.staffList
          })
        }
      })
    })
  },
  showModal(e) {
    const id = e.currentTarget.dataset.id
    this.selectComponent('#' + id).show()
  },
  bindChangeFirst(e) {
    this.setData({
      first: e.detail.value
    })
    this.updateDisabled()
  },
  bindChangeResponsible(e) {
    this.setData({
      hospitalStaffName: e.detail.label,
      hospitalStaffId: e.detail.value
    })
    this.updateDisabled()
  },
  /**
   * 输入事件
   */
  bindinput(e) {
    const name = e.currentTarget.dataset.name
    this.setData({
      [name]: e.detail.value,
      [name + 'Err']: false
    })
    this.updateDisabled()
  },
  updateDisabled() {
    if (this.data.addFrom.typessd == 0) {
      this.setData({
        disabled: !(this.data.name && this.data.mobile && this.data.hospitalStaffId && this.data.hospitalStaffName)
      })
    } else {
      this.setData({
        disabled: false
      })
    }

  },
  onShow() {
    if (wx.getStorageSync('isT') == 1) {
      wx.reLaunch({
        url: '/pages/workbench/workbench',
      })
    }
    this.setData({
      isLock: null,
      modelid: wx.getStorageSync('modelid')
    })
    wx.hideLoading()
  },
  bindtapNext() {
    let that = this
    let lock = null
    let locationEnabled = false
    let locationAuthorized = false
    let bluetoothEnabled = false
    if (!that.data.isLock) {
      that.setData({
        isLock: new Date().getTime()
      })
    } else {
      lock = new Date().getTime()
    }
    if (that.data.isLock && lock) {
      if (lock - that.data.isLock < app.globalData.isNumLock) {
        return
      } else {
        that.setData({
          isLock: lock
        })
      }
    }
    const {
      name,
      mobile,
      hospitalStaffId,
      payId,
      mark,
      hospitalStaffName,
      patientId
    } = this.data
    wx.getSystemInfo({
      success(resd) {
        console.log(resd, '设备');
        locationEnabled = resd.locationEnabled; //判断手机定位服务是否开启
        locationAuthorized = resd.locationAuthorized; //判断定位服务是否允许微信授权
        bluetoothEnabled = resd.bluetoothEnabled; //判断蓝牙服务是否开启
        if (!locationEnabled) {
          that.showDialog({
            title: '手机未打开定位功能',
            icon: 'fail',
            tip: ['']
          })
          wx.closeBluetoothAdapter()
          that.setData({
            btnFis: false
          })
        } else if (!locationAuthorized) {
          that.showDialog({
            title: '微信未授权定位权限',
            icon: 'fail',
            tip: ['请前往设置-应用内打开', '微信定位信息权限']
          })
          wx.closeBluetoothAdapter()
          that.setData({
            btnFis: false
          })
        } else if (!bluetoothEnabled) {
          that.showDialog({
            title: '手机蓝牙未打开',
            icon: 'fail',
            tip: ['请前往设置-应用内打开', '手机蓝牙']
          })
          wx.closeBluetoothAdapter()
          that.setData({
            btnFis: false
          })
        } else {
          wx.getSetting({
            success: res => {
              console.log(res);
              let authSetting = res.authSetting
              if (authSetting['scope.userLocation']) {
                if (authSetting['scope.bluetooth']) {
                  wx.showLoading({
                    title: '下单中...',
                    icon: 'none',
                    mask: true
                  })
                  if (that.data.addFrom.typessd == 0) {
                    if (validate(that, 'name', 'mobile')) {
                      that.setData({
                        'addFrom.username': name,
                        'addFrom.phone': mobile,
                        'addFrom.institutionFeeId': payId,
                        'addFrom.hospitalStaffId': hospitalStaffId,
                        'addFrom.hospitalStaffName': hospitalStaffName,
                        'addFrom.buyerId': patientId,
                        'addFrom.remark': mark,
                      })
                      wx.request({
                        url: app.globalData.serverUrl + '/medical/device/order',
                        method: 'POST',
                        header: {
                          'token': wx.getStorageSync('token')
                        },
                        data: that.data.addFrom,
                        success: res => {
                          let resp = res.data
                          if (resp.code == 200) {
                            wx.hideLoading()
                            console.log(resp.data.orderInfo);
                            if (resp.data.orderInfo.operationType == 1 && resp.data.orderInfo.equipmentDeposit == 0) {
                              let command = resp.data.orderInfo.treatmentIds
                              //激活项目指令
                              let commandArr = 'AA12' + that.binaryToHex(command) + '00BBFFFFFFFFFFFFFFFFFFFFFF'
                              let commandStartArr = 'AA11' + that.timeToHex(resp.data.orderInfo.projectOfDays, resp.data.orderInfo.treatmentOfDays) + 'DCFFFFFFFFFFFFFFFFFFFFFF'
                              that.setData({
                                commandEnd: commandArr,
                                commandStart: commandStartArr
                              })
                              that.setData({
                                btnFis: true,
                                resp: resp
                              })
                              that.restecode()
                            } else {
                              wx.navigateTo({
                                url: '/pages/equipment/depositCollection/depositCollection?orderInfo=' + JSON.stringify(resp.data.orderInfo),
                              })
                            }
                          } else {
                            wx.hideLoading()
                            wx.showToast({
                              icon: 'none',
                              title: resp.message,
                            })
                          }
                        }
                      })
                      console.log(name, mobile, hospitalStaffId, payId, mark, hospitalStaffName, patientId);
                    }else{
                      wx.hideLoading()
                    }
                  } else {
                    that.setData({
                      'addFrom.username': name,
                      'addFrom.phone': mobile,
                      'addFrom.institutionFeeId': payId,
                      'addFrom.hospitalStaffId': hospitalStaffId,
                      'addFrom.hospitalStaffName': hospitalStaffName,
                      'addFrom.buyerId': patientId,
                      'addFrom.remark': mark,
                    })
                    console.log(that.data.addFrom, '最后');
                    wx.request({
                      url: app.globalData.serverUrl + '/medical/device/order',
                      method: 'POST',
                      header: {
                        'token': wx.getStorageSync('token')
                      },
                      data: that.data.addFrom,
                      success: res => {
                        let resp = res.data
                        if (resp.code == 200) {
                          console.log(resp.data.orderInfo);
                          if (resp.data.orderInfo.operationType == 1 && resp.data.orderInfo.equipmentDeposit == 0) {
                            let command = resp.data.orderInfo.treatmentIds
                            //激活项目指令
                            let commandArr = 'AA12' + that.binaryToHex(command) + '00BBFFFFFFFFFFFFFFFFFFFFFF'
                            let commandStartArr = 'AA11' + that.timeToHex(resp.data.orderInfo.projectOfDays, resp.data.orderInfo.treatmentOfDays) + 'DCFFFFFFFFFFFFFFFFFFFFFF'
                            that.setData({
                              commandEnd: commandArr,
                              commandStart: commandStartArr
                            })
                            that.setData({
                              btnFis: true,
                              resp: resp
                            })
                            that.restecode()
                          } else {
                            wx.navigateTo({
                              url: '/pages/equipment/depositCollection/depositCollection?orderInfo=' + JSON.stringify(resp.data.orderInfo),
                            })
                          }
                        } else {
                          wx.showToast({
                            icon: 'none',
                            title: resp.message ? resp.message : '',
                          })
                        }
                      }
                    })
                  }
                } else {
                  that.showDialogsq({
                    title: '请给予蓝牙权限',
                    icon: 'warning',
                    tip: ['']
                  })
                }
              } else {
                that.showDialogsq({
                  title: '请给予微信定位权限',
                  icon: 'warning',
                  tip: ['']
                })
              }
            }
          })
        }
      },
      fail() {
        that.showDialog({
          title: '手机未打开定位功能',
          icon: 'fail',
          tip: ['']
        })
      }
    })
  },
  //设备指令 蓝牙数据
  startBluetoothDeviceDiscovery() {
    let that = this;
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log(res);
        //已打开
        wx.getBluetoothAdapterState({
          //蓝牙的匹配状态
          success: (res1) => {
            console.log(res1, "本机设备的蓝牙已打开");
            //生成密钥存储
            console.log('开始搜索蓝牙设备')
            wx.startBluetoothDevicesDiscovery({
              success: (res) => {
                console.log(res, '搜索到的设备');
                // // 发现外围设备
                wx.showLoading({
                  title: '设备搜索中',
                  mask: true
                })
                that.getDeviceId().then(response => {
                  console.log(response, '查看返回值');
                  if (response == undefined) {
                    that.showDialog({
                      title: '设备蓝牙未打开',
                      icon: 'fail',
                      tip: ['请检查设备蓝牙是否打开；', '设备电量是否充足。']
                    })
                    wx.closeBluetoothAdapter()
                    return
                  }
                  //生成密钥存储
                  let keys;
                  keys = response.newdeviceId.split(':')
                  wx.setStorageSync('key_K', that.keysfun(keys))
                  that.setData({
                    deviceId: response.deviceId,
                    btnFis: false
                  })
                  try {
                    wx.setStorageSync('deviceId', that.data.deviceId)
                  } catch (e) {
                    //TODO handle the exception
                  }
                  let deviceId = response.deviceId;
                  if (deviceId) {
                    wx.createBLEConnection({
                      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
                      deviceId,
                      success(rest) {
                        wx.hideLoading()
                        setTimeout(() => {
                          that.getBLEDeviceServices(deviceId);
                        }, 1000)
                        wx.stopBluetoothDevicesDiscovery({
                          success(res) {}
                        });
                      },
                      fail(err) {
                        console.log(err);
                      }
                    });
                  }
                })
              }
            })
          },
          fail(error) {
            that.showDialog({
              title: '手机蓝牙未打开',
              icon: 'fail',
              tip: ['请前往设置-应用内打开', '手机蓝牙']
            })
            that.setData({
              btnFis: false
            })
          },
        });
      },
      fail: (err) => {
        console.log(err);
        that.showDialog({
          title: '手机蓝牙未打开',
          icon: 'fail',
          tip: ['请前往设置-应用内打开', '手机蓝牙']
        })
        that.setData({
          btnFis: false
        })
      }
    })
  },
  //密钥生成
  keysfun(data) {
    let that = this
    let strs = '545a5a59' + data.join('')
    data.map((item, index) => {
      let F = parseInt(('0x' + item)) + parseInt(('0x0' + (index + 1)))
      strs += F.toString(16)
    })
    return strs
  },
  getBLEDeviceServices(deviceId) {
    let that = this;
    wx.getBLEDeviceServices({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId,
      success: (res) => {
        console.log(res, '连接成功返回值');
        wx.onBLEConnectionStateChange(function (res) {
          // 该方法回调中可以用于处理连接意外断开等异常情况
          if (!res.connected) {
            that.showDialog({
              title: '蓝牙已断开',
              icon: 'fail',
              tip: ['请重新扫码连接']
            })
            wx.offBLEConnectionStateChange()
            setTimeout(() => {
              wx.navigateBack({
                delta: 2,
              })
            }, 2000)
          }
        })
        if (res.services) {
          let resA = res.services
          res.services.map((item, index) => {
            if (item.isPrimary) {
              wx.getBLEDeviceCharacteristics({
                deviceId,
                serviceId: item.uuid,
                success: (resServe) => {
                  console.log(resServe, '蓝牙服务');
                  resServe.characteristics.map(vtm => {
                    if (vtm.uuid == '0000FFF6-0000-1000-8000-00805F9B34FB') {
                      that.setData({
                        UUID1: resA[index].uuid,
                        UUID2: vtm.uuid
                      })
                      try {
                        wx.setStorageSync('UUID1',
                          that.data.UUID1)
                        wx.setStorageSync('UUID2',
                          that.data.UUID2)
                      } catch (e) {
                        //TODO handle the exception
                      }
                      that.notifyBLECharacteristicValueChange(
                        deviceId, that.data.UUID1,
                        that.data.UUID2, true);
                    }
                  })
                }
              })
              console.log(item.uuid, '设备UUID');
            }
          })

        }
      }
    })
  },
  // 向蓝牙写入数据
  BleWrite(instruction, characteristicIdA, serviceIdA) {
    // 向蓝牙设备发送一个0x00的16进制数据
    let _this = this
    _this.setData({
      type: 1
    })
    // let serviceId = _this.serviceId
    let serviceId = serviceIdA;
    let characteristicId = characteristicIdA;
    let deviceId = _this.data.deviceId
    // const buffer = _this.hexStringToArrayBuffer(instruction);
    // const buffer = _this.hexStringToArrayBuffer1(instruction);
    const buffer = _this.hex2ArrayBuffer(instruction);
    console.log('buffer=======================', buffer)
    wx.writeBLECharacteristicValue({
      deviceId, // 蓝牙设备 deviceId
      serviceId, // 蓝牙服务uuid,即第二个uuid
      characteristicId, // 蓝牙特征值的 (即 writeId)
      value: buffer, // 这里的value是ArrayBuffer类型
      success(res) {
        console.log('指令下发成功==', res.errMsg, res)
        console.log('指令下发成功传入的参数--characteristicId', characteristicId, '--serviceId：',
          serviceId)
        wx.readBLECharacteristicValue({
          // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接  
          deviceId: deviceId,
          // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取  
          serviceId: serviceId,
          // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取  
          characteristicId: characteristicId,
          success: (res) => {
            console.log('readBLECharacteristicValue:success', res)
          },
          fail: (res) => {
            console.log('readBLECharacteristicValue:fail', res)
          }
        })
      },
      fail(err) {
        console.log('写入数据失败', err)
        console.log('指令下发失败传入的参数--characteristicId', characteristicId, '--serviceId：',
          serviceId)
        wx.showToast({
          icon: "none",
          title: "请确保您的手机已连接设备",
          duration: 3000
        })
      }
    })
  },
  //监听开始和取消
  async notifyBLECharacteristicValueChange(deviceId, serviceId, characteristicId, state) {
    let that = this;
    wx.notifyBLECharacteristicValueChange({
      state: state, // 启用 notify 功能
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId,
      // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
      serviceId,
      // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
      characteristicId,
      success(res) {
        that.BleWrite(encryptionData(that.data.commandStart, wx.getStorageSync('key_K')), that.data.UUID2, that.data.UUID1)
        wx.showLoading({
          title: '正在充值...',
          mask: true
        })
        console.log(res, '监听的值看看');
        if (!state) {
          that.notifyBLECharacteristicValueChange(that.data.deviceId, that.data.serviceId, that.data
            .characteristicId, true);
        }
        wx.onBLECharacteristicValueChange(
          function (resa) {
            if (that.data.type == 1) {
              let a = that.buf2hex(resa.value)
              // console.log('监听成功1', a, '----', that.ab2hex(resa.value))
              let successAC = decryptData(a, wx.getStorageSync('key_K')).substr(0, 8)
              console.log(successAC, '成功截取');
              if (successAC == 'aa1101ba') {
                wx.hideLoading()
                wx.showLoading({
                  title: '正在激活...',
                  mask: true
                })
                that.BleWrite(encryptionData(that.data.commandEnd, wx.getStorageSync('key_K')), that.data.UUID2, that.data.UUID1)
              }

              if (successAC == 'aa1102ba') {
                wx.hideLoading()
                that.showDialog({
                  title: '充值失败',
                  icon: 'fail',
                  tip: ['请重新操作']
                })
                setTimeout(() => {
                  wx.navigateBack({
                    delta: 1,
                  })
                }, 1000)
              }
              if (successAC == 'aa1201b9') {
                wx.request({
                  url: app.globalData.serverUrl + '/device/down',
                  method: 'POST',
                  header: {
                    'token': wx.getStorageSync('token')
                  },
                  data: {
                    deviceNo: that.data.deviceNo,
                    orderNo: that.data.orderNo
                  },
                  success: (res => {
                    if (res.data.code == 200) {
                      wx.offBLEConnectionStateChange()
                      wx.hideLoading({
                        success: (res) => {
                          that.showDialog({
                            title: '传输成功',
                            icon: 'success',
                            tip: ['可以使用设备进行治疗了！']
                          })
                          wx.removeStorageSync('deviceId')
                          wx.removeStorageSync('UUID1')
                          wx.removeStorageSync('UUID2')
                          wx.removeStorageSync('key_K')
                          wx.removeStorageSync('chb_key')
                          if (wx.getStorageSync('deviceId')) {
                            wx.closeBLEConnection({
                              deviceId: wx.getStorageSync('deviceId'),
                              success(res) {},
                              fail(res) {}
                            })
                          }
                          wx.closeBluetoothAdapter()
                          setTimeout(() => {
                            wx.navigateBack({
                              delta: 2,
                            })
                          }, 1500)
                        },
                      })
                    } else {
                      // AA14BEFFFFFFFFFFFFFFFFFFFFFFFFFF
                      that.BleWrite(encryptionData("AA14BEFFFFFFFFFFFFFFFFFFFFFFFFFF", wx.getStorageSync('key_K')), that.data.UUID2, that.data.UUID1)
                    }
                  })
                })
              }
              if (successAC == 'aa1202b9') {
                wx.hideLoading()
                that.showDialog({
                  title: '激活失败',
                  icon: 'fail',
                  tip: ['请重新操作']
                })
                that.BleWrite(encryptionData("AA14BEFFFFFFFFFFFFFFFFFFFFFFFFFF", wx.getStorageSync('key_K')), that.data.UUID2, that.data.UUID1)
              }
              if (successAC == 'aa1401bf') {
                wx.closeBluetoothAdapter()
                wx.navigateBack({
                  delta: 1,
                })
              }
            }
          }
        );
      },
      fail(err) {
        console.log('报错了1', err)
      }
    });
  },
  // 发现外围设备
  getDeviceId() {
    let that = this;
    console.log("执行到这--发现外围设备1")
    return new Promise(function (resolve, reject) {
      let deviceId;
      let timer = setTimeout(() => {
        if (!deviceId) {
          wx.hideLoading()
          console.log('清理蓝牙监听', res)
          that.showDialog({
            title: '设备蓝牙未打开',
            icon: 'fail',
            tip: ['']
          })
          wx.closeBluetoothAdapter()
          resolve(undefined);
          clearTimeout(timer);
          timer = null
        }
      }, 5000);
      wx.onBluetoothDeviceFound(function (devices) {
        console.log('发现的设备2', devices, '-----------', that.data.BTLTEST)
        // if(wx.getStorageSync('modelid')!='当前设备是其他类型'){
        let newdeviceId = that.addObjretIphone(devices.devices[0].name.slice(devices.devices[0].name.indexOf(' ') + 1))
        console.log(newdeviceId, '-----------', that.data.BTLTEST);
        if (newdeviceId == that.data.BTLTEST) {
          deviceId = devices.devices[0].deviceId;
          let a;
          a = {
            deviceId: devices.devices[0].deviceId,
            newdeviceId: newdeviceId
          }
          resolve(a);
          clearTimeout(timer);
          timer = null
        }
      });
    });
  },
  // 16进制字符串转ArrayBuffer
  hex2ArrayBuffer(hex_str) {
    // let hex_str = 'AA5504B10000B5'
    let typedArray = new Uint8Array(hex_str.match(/[\da-f]{2}/gi).map(function (h) {
      return parseInt(h, 16)
    }))
    let buffer = typedArray.buffer
    return buffer
  },
  // ArrayBuffer转16进度字符串
  buf2hex(arrayBuffer) {
    return Array.prototype.map.call(new Uint8Array(arrayBuffer), x => ('00' + x.toString(16)).slice(-2))
      .join('');
  },
  //处理字符
  addObjretIphone(data) {
    let result = "";
    let newarr = []
    for (let i = 0; i < data.length; i++) {
      if (i % 2 == 0 && i != 0) {
        result += ':' + data[i];
      } else {
        result += data[i];
      }
    }
    newarr = result.split(':')
    return newarr.reverse().join(':')
  },
  addObjret(data) {
    let result = "";
    for (let i = 0; i < data.length; i++) {
      if (i % 2 == 0 && i != 0) {
        result += ':' + data[i];
      } else {
        result += data[i];
      }
    }
    return result
  },
  // bit转换
  binaryToHex(binary) {
    let arrayD = ['项目治疗一', '项目治疗二', '常规催乳', '乳汁分泌少', '乳腺管不通', '子宫复旧', '产后排尿', '产后恢复']
    let bitStr = '00000000'
    binary.map(item => {
      bitStr = bitStr.substring(0, 7 - item) + '1' + bitStr.substring(7 - item + 1)
    })
    const decimal = new Number(`0b${bitStr}`);
    let hexadecimal = decimal.toString(16);
    if (hexadecimal.length == 1) {
      hexadecimal = '0' + hexadecimal
    }
    return hexadecimal.toUpperCase();
  },
  //时间转换
  timeToHex(timeDays, sum) {
    // let endTime = ''
    timeDays = Number(timeDays) * Number(sum) * 60
    let hex16 = timeDays.toString(16).toUpperCase()
    if (hex16.length % 2 == 0) {
      if (hex16.length == 2) {
        return hex16 + '00'
      }
      return hex16.substring(2) + hex16.substring(0, 2)
    } else {
      hex16 = '0' + hex16
      return hex16.substring(2) + hex16.substring(0, 2)
    }
  },
})